#ifndef NETWORK_H
#define NETWORK_H

#include <QAbstractSocket>
#include <QHash>
#include <QHostAddress>
#include <QJsonObject>
#include "server.h"

class PeerManager;
class FileServer;
class FileClient;
class Network : public QObject
{
    Q_OBJECT

public:
    Network(QObject *parent = Q_NULLPTR);

    bool hasConnection(const QHostAddress &senderIp, int port) const;

signals:
    void newMessage(QObject *connection, const QVariantMap &message);
    void newParticipant(QObject *connection);
    void participantLeave(QObject *connection);

    void newFile(const QObject *connection, const QVariantMap &message);
    void fileClosed(const QObject *connection);
    void progress(const QObject *connection, qint64 received, qint64 total);
    void shopDetection(const QUrl &url);
public slots:
    bool listen(const QString &identity);


    void sendMessage(QObject *connection, const QVariantMap &message);

    void sendFile(const QString &fileName, const QString &identity);
    void sendFile(const QString &fileName);

    void receiveFile(const QVariantMap &message);

    void cancelFileServerTransport(const QString &token);
    void cancelFileClientTransport(const QString &token);
private slots:
    void newConnection(Connection *connection);
    void newConnection(const QHostAddress &address, int port);
    void connectionError(QAbstractSocket::SocketError socketError);
    void disconnected();
    void readyForUse();

private:
    void removeConnection(Connection *connection);

    PeerManager *peerManager;
    Server server;
    QString m_identity;
    QMultiHash<QHostAddress, Connection *> peers;
    QMultiHash<QHostAddress, int> peerTemps;
    QList<FileServer *> m_fileServer;
    QList<FileClient *> m_fileClient;
    QList<quint16> m_ports;
};

#endif
